package _17_剑指Offer;

import _17_剑指Offer.datastrcute.TreeNode;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

public class _37_剑指Offer序列化二叉树重构 {

    private static final String EMPTY = "#";

    private static final String SPLIT = "!";

    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder sb = new StringBuilder();
        preTraverse(root, sb);
        return sb.toString();
    }

    // 1!2!#!#!3!4!#!#!5!#!#!
    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(SPLIT);
        // 使用链表结构，因为这样删除的都是前面的数据，使用链表比较适合
        List<String> list = new LinkedList<>(Arrays.asList(split));
        return deserialize(list);
    }

    public TreeNode deserialize(List<String> list) {
        String value = list.remove(0);
        if (EMPTY.equals(value)) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(value));

        root.left = deserialize(list);

        root.right = deserialize(list);
        return root;
    }

    private void preTraverse(TreeNode root, StringBuilder sb) {
        if (root == null) {
            sb.append(EMPTY).append(SPLIT);
            return;
        }
        sb.append(root.val).append(SPLIT);
        preTraverse(root.left, sb);
        preTraverse(root.right, sb);
    }

}
